import uuid
import requests

from django.shortcuts import render
import json
from rest_framework.views import APIView

from utils.OSSClient import OSSClient
from utils.jsonResponse import SuccessResponse, ErrorResponse

url = "https://api.siliconflow.cn/v1/chat/completions"

# Create your views here.

class UploadImageByIdView(APIView):

    def post(self, request):
        # 检查请求中是否包含文件
        if 'image' not in request.FILES:
            return ErrorResponse(msg="没有文件上传")

        image = request.FILES['image']
        filename = f"{uuid.uuid4().hex}-{image.name}"  # 可以根据需求自定义路径
        oss_client = OSSClient()
        file_url = oss_client.upload_file(image, filename)
        if file_url:
            return SuccessResponse(data=file_url)
        else:
            return ErrorResponse(msg="文件上传失败")

class ChatView(APIView):
    def post(self, request):
        question = request.POST.get('question')
        payload = {
            "model": "Qwen/QwQ-32B",
            "messages": [
                {
                    "role": "system",
                    "content": "你是一个学生画像助手，需要用口语化的现代中文回答用户问题"
                },
                {
                    "role": "user",
                    "content":  question
                }
            ],
            "stream": False,
            "max_tokens": 512,
            "stop": None,
            "temperature": 0.7,
            "top_p": 0.7,
            "top_k": 50,
            "frequency_penalty": 0.5,
            "n": 1,
            "response_format": {"type": "text"},
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "description": "<string>",
                        "name": "<string>",
                        "parameters": {},
                        "strict": False
                    }
                }
            ]
        }
        headers = {
            "Authorization": "Bearer sk-eqhcujhywbztvzjjzethpvricglgnffihatqakpzijlsweuh",
            "Content-Type": "application/json"
        }

        try:
            # 发送API请求
            response = requests.post(
                url,  # 请确保这里已经定义了正确的API地址
                json=payload,
                headers=headers,
            )
            response.raise_for_status()  # 检查HTTP错误

            # 解析响应
            response_data = response.json()

            # 提取content内容
            content = response_data["choices"][0]["message"]["content"]

            # 返回清洗后的内容
            return SuccessResponse(data=content)

        except requests.exceptions.RequestException as e:
            # 处理网络请求错误
            return SuccessResponse(f"API请求失败: {str(e)}", status=500)
        except ErrorResponse as e:
            # 处理JSON解析错误
            return SuccessResponse(f"响应解析失败: {str(e)}", status=500)




